const log4js = require('../utils/logUtils');
const logger = log4js.getLogger('web');
const settingModel = require("../model/setting");
const ffmpeg = require('fluent-ffmpeg');
const config = require("../db/config");
const directoryUtils = require("../utils/directoryUtils");
const moment = require("moment");
const deviceCache = require("../db/deviceCache");

const TAG = "[ffmpegUtils]";
module.exports = {

    /**
     * 使用fluent-ffmpeg截图
     */
    snap(source, deviceid, channel) {
        logger.info('snap to', settingModel.cache.snap_path, deviceid + "_" + channel + ".jpg", 'source', source);

        return new Promise(function (resolve, reject) {
            if (!channel || channel === 'undefined') {
                reject();
                return;
            }
            ffmpeg({source: source, timeout: 20})
                .on('filenames', function (filenames) {
                    let ret = settingModel.cache.snap_path || '';
                    let last = ret.charAt(ret.length - 1);
                    if (last !== '/') ret = ret + '/';
                    let first = ret.charAt(0);
                    if (first === '.') ret = ret.substring(1, ret.length);
                    if (ret.indexOf('/public') === 0) {
                        ret = ret.replace('/public', '');
                    }
                    resolve(ret + filenames);
                })
                .on('end', function () {
                    logger.log('ffmpeg end');
                })
                .on('stderr', function (stderrLine) {
                    logger.log('Stderr output: ' + stderrLine);
                })
                .on('error', function (err) {
                    logger.log('Cannot process video: error =', err.message);
                }).addOption(['-rtsp_transport tcp'])
                .screenshots({
                    count: 1,
                    // timemarks: [ '00:00:02.000' ],
                    folder: settingModel.cache.snap_path,
                    filename: deviceid + "_" + channel + ".jpg",
                    size: '640x?',
                    timeout: 20
                });
        });
    },
    stopRecord(ffmpegProcess) {
        return new Promise((resolve, reject) => {
            // 发送SIGTERM信号给ffmpeg子进程
            if (ffmpegProcess) {
                ffmpegProcess.kill();
                resolve();
            } else {
                resolve();
            }
        });
    },
    // 录像
    startRecordFfmpeg(camera) {
        const channel = camera.channel_id
        const deviceid = camera.deviceid;

        // 目录格式是创建年/月/日/通道名称 多级目录，文件名是取当前时间，如20220202_10:22:11.mkv
        // filepath里要有年月日三级
        const now = moment();
        const year = now.format('YYYY');
        const month = now.format('MM');
        const day = now.format('DD');
        // 格式化字符串为YYYYMMDD_HHmmss
        const str = now.format('YYYYMMDD-HHmmss');
        const filename = `${str}.mkv`;
        let filepath = `${config.record.path}/${year}/${month}/${day}/${deviceid}/${channel}/`;
        // 自动检查多级目录是否存在并创建
        directoryUtils.ensureDirectoryByPath(filepath);

        // 改最后一个文件名
        directoryUtils.renameLastFile(filepath);

        logger.info(TAG, "创建ffmpeg对象", filename);
        let process = ffmpeg({source: camera.mrl});
        process.on('stderr', function (stderrLine) {
            // logger.error(TAG, 'Stderr output: ' + stderrLine);
        }).on('error', function (err) {
            logger.log(TAG, 'Cannot process video: error =', err.message, deviceid, channel);
            // 改最后一个文件名
            directoryUtils.renameLastFile(filepath);
        }).on('start', function(ffmpegCommand){
            // 从ffmpegCommand 里解析出来 源地目标地址
            //  ffmpeg -i rtsp://admin:abcd123456@192.168.4.31:554/1/2 -y -py /mnt/record1/2024/01/22/41010500002000000005/preview/20240122-131235.mkv
            const array = ffmpegCommand.split(' ');
            const target = array.pop();
            const pathArray = target.split('/');
            const channelId = pathArray[pathArray.length - 2];
            const camera = deviceCache.getCameraByChannelId(channelId);
            camera.recording=true;
            camera.recordFilePath = target;
            logger.info(TAG, "开始录像", ffmpegCommand);
        }).outputOptions(['-c copy']);

        process.output(filepath + filename);
        process.run();
        return process;
    },
};
